package com.modules.common.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;

/**
 * Base64FileUtils
 *
 * @author yzz
 * @date 2024-04-02 14:47
 **/
public class Base64FileUtils {

    public static InputStream base64ToInputStream(String base64String) {
        byte[] fileContent = Base64.getDecoder().decode(base64String);
        return new ByteArrayInputStream(fileContent);
    }

    public static File base64ToFile(String base64String) {
        byte[] fileContent = Base64.getDecoder().decode(base64String);
        File file = null;
        try {
            file = File.createTempFile("temp", ".base64");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Path path = Paths.get(file.getAbsolutePath());
        try {
            Files.write(path, fileContent, StandardOpenOption.CREATE);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return file;
    }

    public static void base64ToFile(String base64String, String outputFilePath) {
        byte[] fileContent = Base64.getDecoder().decode(base64String);
        Path path = Paths.get(outputFilePath);
        try {
            Files.write(path, fileContent, StandardOpenOption.CREATE);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String fileToBase64(String filePath) {
        byte[] fileContent = new byte[0];
        try {
            fileContent = Files.readAllBytes(Paths.get(filePath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Base64.getEncoder().encodeToString(fileContent);
    }

}
